package com.limh.socketdemo.service.utils

import android.content.Context
import android.net.wifi.WifiManager
import android.util.Log
import java.io.*
import java.util.*

/**
 * @author limh
 * @function
 * @date 2018/4/27 15:41
 */
object StreamToolkit {
    private val TAG = "StreamToolkit"
    @Throws(IOException::class)
    fun readLine(nis: InputStream): String? {
        val sb = StringBuilder()
        var c1 = 0
        var c2 = 0
        while (c2 != -1 && !(c1 == '\r'.toInt() && c2 == '\n'.toInt())) {
            c1 = c2
            c2 = nis.read()
            sb.append(c2.toChar())
        }
        return if (sb.isEmpty())
            null
        else
            sb.toString()
    }

    fun readContent(nis: InputStream): String? {
        val reader = BufferedReader(InputStreamReader(nis, "UTF-8"))
        val sb = StringBuilder()
        var c1 = 0
        var c2 = 0
        while (c2 != -1 && !(c1 == '\r'.toInt() && c2 == '\n'.toInt())) {
            c1 = c2
            c2 = reader.read()
            sb.append(c2.toChar())
        }
        return if (sb.isEmpty())
            null
        else
            sb.toString()
    }

    @Throws(IOException::class)
    fun readRawFromStream(fis: InputStream): ByteArray? {
        val bos = ByteArrayOutputStream()
        val buffer = ByteArray(10240)
        var nreaded = 0
        while (fis.read(buffer).apply { nreaded = this } > 0) {
            bos.write(buffer, 0, nreaded)
        }
        return bos.toByteArray()
    }

    fun addContentType(suffix: String): String {
        val type = when {
            suffix.endsWith(".html") -> "Content-Type: text/html"
            suffix.endsWith(".js") -> "Content-Type: application/x-javascript"
            suffix.endsWith(".css") -> "Content-Type: text/css"
            suffix.endsWith(".jpg") -> "Content-Type: image/jpeg"
            suffix.endsWith(".png") -> "Content-Type: image/png"
            suffix.endsWith(".ico") -> "Content-Type: image/x-icon"
            else -> "Content-Type: application/json; charset=UTF-8"
        }
        Log.d(TAG, "type=$type")
        return type
    }

    /**
     * 产生1024~65535范围的随机数
     */
    fun getPort(): Int {
        val rand = Random()
        val port = rand.nextInt(64511) + 1024
        Log.d("--util--", "random port=$port")
        return port
    }

    /**
     * 获取当前IP地址
     */
    fun getLocalIp(context: Context): String {
        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        val ipAddress = wifiInfo.ipAddress
        return if (ipAddress == 0) {
            ""
        } else {
            ((ipAddress and 0xff).toString() + "." + (ipAddress shr 8 and 0xff) + "."
                    + (ipAddress shr 16 and 0xff) + "." + (ipAddress shr 24 and 0xff))
        }
    }
}
